package com.sihai.ehr.service.impl;

import java.text.MessageFormat;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.math.NumberUtils;
import org.hibernate.Query;
import org.hibernate.Session;
import org.springframework.stereotype.Service;
import org.springframework.util.Assert;

import com.sihai.core.DataAccessor;
import com.sihai.core.DynamicQuery;
import com.sihai.core.Limit;
import com.sihai.core.LimitedList;
import com.sihai.core.QueryCreator;
import com.sihai.core.Sorter;
import com.sihai.ehr.model.biz.EmployeeinfoWork;
import com.sihai.ehr.model.biz.SalaryCustom;
import com.sihai.ehr.model.biz.SalaryCustomConfig;
import com.sihai.ehr.model.biz.SalaryCustomDetail;
import com.sihai.ehr.model.sys.SalaryFrameworkEnum;
import com.sihai.ehr.service.SalaryCustomService;

/**
 * 自定义薪资管理服务实现
 * 
 * @author henry
 * 
 */
@Service("salaryCustomService")
public class SalaryCustomServiceImpl implements SalaryCustomService {

	@Resource
	private DataAccessor dataAccessor;

	@Override
	public SalaryCustom get(Long id) {
		if (id == null || id < 0) {
			throw new RuntimeException("【传入参数非法】");
		}
		try {
			return dataAccessor.get(SalaryCustom.class, id);
		} catch (Exception e) {
			throw new RuntimeException("【异常原因：获取自定义薪资架构明细数据库发生异常】【异常说明：+" + e.getMessage() + "】【发生地点：SalaryCustomServiceImpl.get;参数id=" + id + " 】");
		}
	}

	@Override
	public void save(SalaryCustom custom) {
		if (custom == null || custom.getOrganization() == null) {
			throw new RuntimeException("【custom对象参数异常】");
		}
		try {
			dataAccessor.saveOrUpdate(custom);
		} catch (Exception e) {
			throw new RuntimeException("【异常原因：保存自定义薪资架构对象到数据库发生异常】【异常说明：" + e.getMessage() + "】【发生地点：SalaryCustomServiceImpl.save】");
		}
	}

	@Override
	public void deleteCustoms(final String ids) {
		if (ids == null || ids.isEmpty()) {
			throw new RuntimeException("【参数异常：ids为空】");
		}
		try {
			// 第一步删除设置
			dataAccessor.batchUpdate(new QueryCreator() {
				@Override
				public Query createQuery(Session session) {
					return session.createQuery(MessageFormat.format("delete from SalaryCustomConfig s where s.salaryCustom.id in ({0})", ids));
				}
			});
			
			//第二步删除细节
			dataAccessor.batchUpdate(new QueryCreator() {
				@Override
				public Query createQuery(Session session) {
					return session.createQuery(MessageFormat.format("delete from SalaryCustomDetail s where s.salaryCustom.id in ({0})", ids));
				}
			});

			dataAccessor.batchUpdate(new QueryCreator() {
				@Override
				public Query createQuery(Session session) {
					return session.createQuery(MessageFormat.format("delete from SalaryCustom s where s.id in ({0})", ids));
				}
			});
		} catch (Exception e) {
			throw new RuntimeException("【异常原因：移出自定义新姿架构信息数据库发生异常】【异常说明：" + e.getMessage() + "】【发生地点：SalaryCustomServiceImpl.deleteCustoms】");
		}
	}

	@Override
	public void deleteCustomDetails(final Long customId) {
		if (customId == null && customId <= 0) {
			throw new RuntimeException("【参数异常：customId参数错误】");
		}
		try {
			dataAccessor.batchUpdate(new QueryCreator() {
				@Override
				public Query createQuery(Session session) {
					return session.createQuery(MessageFormat.format("delete from SalaryCustomDetail d where d.salaryCustom.id={0}", customId));
				}
			});
		} catch (Exception e) {
			throw new RuntimeException("【异常原因：移出自定义薪资架构细节信息数据库发生异常】【异常说明：" + e.getMessage() + "】【发生地点：SalaryCustomServiceImpl.deleteCustomDetails】");
		}
	}

	@Override
	public LimitedList<SalaryCustom> find(final Long organizationId, Limit limit, Sorter sorter) {
		if (organizationId == null || organizationId < 0) {
			throw new RuntimeException("【传入参数非法】");
		}
		try {
			return dataAccessor.findByQuery(SalaryCustom.class, new QueryCreator() {

				@Override
				public Query createQuery(Session session) {
					DynamicQuery dynamicQuery = new DynamicQuery("from SalaryCustom s where 1 <> 2");
					dynamicQuery.appendIfNotNull("and s.organization.id =:organizationId", "organizationId", organizationId);
					return dynamicQuery.build(session);
				}
			}, limit, sorter);
		} catch (Exception e) {
			throw new RuntimeException("【异常原因：获取自定义薪资列表时数据库发生异常】【异常说明：+" + e.getMessage() + "】【发生地点：SalaryCustomServiceImpl.find;参数organizationId=" + organizationId + "】");
		}
	}

	@Override
	public SalaryCustomDetail getCustomDetailByIdAndLnkType(final Long id, final SalaryFrameworkEnum frameworkEnum) {
		if (id == null || frameworkEnum == null) {
			throw new RuntimeException("【id或frameworkEnum对象参数异常】");
		}
		try {
			List<SalaryCustomDetail> listDetails = dataAccessor.findByQuery(SalaryCustomDetail.class, new QueryCreator() {

				@Override
				public Query createQuery(Session session) {
					DynamicQuery dynamicQuery = new DynamicQuery("from SalaryCustomDetail s where 1 <> 2");
					dynamicQuery.appendIfNotNull("and s.salaryCustom.id =:id", "id", id);
					dynamicQuery.appendIfNotNull("and s.linkedDataType =:linkedDataType", "linkedDataType", frameworkEnum);
					dynamicQuery.append(" limit 1");

					return dynamicQuery.build(session);
				}
			}, null, null);
			if (listDetails != null && listDetails.size() > 0) {
				return listDetails.get(0);
			} else {
				return null;
			}
		} catch (Exception e) {
			throw new RuntimeException(e.getMessage());
		}
	}

	@Override
	public LimitedList<SalaryCustomConfig> getSalaryCustomConfigByWorkId(final Long workId, Limit limit, Sorter sorter) {
		try {
			return dataAccessor.findByQuery(SalaryCustomConfig.class, new QueryCreator() {

				@Override
				public Query createQuery(Session session) {
					DynamicQuery dynamicQuery = new DynamicQuery("from SalaryCustomConfig sc where 1=1 ");
					dynamicQuery.append("and sc.employeeinfoWork.id=:workId", "workId", workId);
					return dynamicQuery.build(session);
				}
			}, limit, sorter);
		} catch (Exception e) {
			throw new RuntimeException("【异常原因：获取自定义薪资列表时数据库发生异常】【异常说明：+" + e.getMessage() + "】【发生地点：SalaryCustomServiceImpl.getSalaryCustomConfigByWorkId;参数workId=" + workId + "】");
		}
	}

	// add.wxn
	// 查找某个自定义薪资架构已设置的人员列表
	public LimitedList<EmployeeinfoWork> findCustomHasSetUsers(Long customId, Limit limit, Sorter sorter) throws Exception {
		return dataAccessor.findByHql(EmployeeinfoWork.class, "select sc.employeeinfoWork from SalaryCustomConfig sc where sc.salaryCustom.id=?", new Object[] { customId }, limit,
				sorter);
	}

	// 查找某个自定义薪资架构未设置的人员列表
	public LimitedList<EmployeeinfoWork> findCustomUnSetUsers(Long customId, final Long organizationId, final Long orgId, final Long dutyId, final Long gradeId,
			final Long gradeLevelId, final Float workYearStart, final Float workYearEnd, Limit limit, Sorter sorter) throws Exception {
		Assert.notNull(customId, "custom id is required");

		final List<Long> list = dataAccessor.findByHql(Long.class, "select sc.employeeinfoWork.id from SalaryCustomConfig sc where sc.salaryCustom.id=?",
				new Object[] { customId }, null, null);

		return dataAccessor.findByQuery(EmployeeinfoWork.class, new QueryCreator() {
			@Override
			public Query createQuery(Session session) {
				DynamicQuery dynamicQuery = new DynamicQuery("from EmployeeinfoWork w where 1=1 ");
				if (organizationId != null && organizationId > 0) {
					dynamicQuery.append("and w.organization.topOrganization is not null and w.organization.topOrganization.id=:organizationId", "organizationId", organizationId);
				}
				if (orgId != null && orgId > 0) {
					// dynamicQuery.append("and w.organization.id=:orgId",
					// "orgId", orgId);
					String treePath = "%," + orgId + ",%";
					dynamicQuery.append("and w.organization.treePath like :treePath", "treePath", treePath);
				}
				if (dutyId != null && dutyId > 0) {
					dynamicQuery.append("and w.duty.id=:dutyId", "dutyId", dutyId);
				}
				if (gradeId != null && gradeId > 0) {
					dynamicQuery.append("and w.grade.id=:gradeId", "gradeId", gradeId);
				}
				if (gradeLevelId != null && gradeLevelId > 0) {
					dynamicQuery.append("and w.gradeLevel.id=:gradeLevelId", "gradeLevelId", gradeLevelId);
				}
				if (list != null && !list.isEmpty()) {
					dynamicQuery.append("and w.id not in (:workIds)", "workIds", list);
				}
				/*
				 * if(workYearStart != null && workYearStart > 0){
				 * dynamicQuery.append("and w.workAge >= :workYearStart",
				 * "workYearStart", workYearStart); } if(workYearEnd != null &&
				 * workYearEnd > 0){
				 * dynamicQuery.append("and w.workAge<= :workYearEnd",
				 * "workYearEnd", workYearEnd); }
				 */

				return dynamicQuery.build(session);
			}
		}, limit, sorter);
	}

	@Override
	public void addUserToCustom(Long customId, String[] workIds) {
		Assert.notNull(customId, "custom id is required");
		Assert.notNull(workIds, "work ids is required");
		SalaryCustom custom = get(customId);
		Assert.notNull(custom, "custom is required");
		for (String id : workIds) {
			Long workId = NumberUtils.createLong(id);
			SalaryCustomConfig config = new SalaryCustomConfig();
			config.setSalaryCustom(custom);
			EmployeeinfoWork work = new EmployeeinfoWork();
			work.setId(workId);
			config.setEmployeeinfoWork(work);
			dataAccessor.save(config);
		}
	}

	@Override
	public void deleteUserFromCustom(final Long customId, final String workIds) {
		Assert.notNull(customId, "custom id is required");
		Assert.notNull(workIds, "work ids is required");
		dataAccessor.batchUpdate(new QueryCreator() {
			@Override
			public Query createQuery(Session session) {
				Query query = session.createQuery(String.format("delete from SalaryCustomConfig sc where sc.salaryCustom.id=:salaryCustomId and sc.employeeinfoWork.id in (%s)",
						workIds));
				query.setParameter("salaryCustomId", customId);
				return query;
			}
		});
	}
	
	@Override
	public Long getTotalCountBySalaryCustomId(final Long customId) {
		if (customId > 0) {
			try {
				return this.dataAccessor.findUnique(Long.class,
						new QueryCreator() {
							@Override
							public Query createQuery(Session session) {
								return session
										.createQuery("select count(s.id) from SalaryCustomConfig s where s.salaryCustom.id="
												+ customId);
							}
						});

			} catch (Exception e) {
				throw new RuntimeException(
						"【统计部门人数异常】【异常原因：:"
								+ e.getMessage()
								+ "】【发生地点：SalaryCustomServiceImpl.getTotalCountBySalaryCustomId】");
			}

		} else {
			return 0L;
		}
	}
}
